#pragma once
#include <iostream>
#include <sys/types.h>          
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include "Log.hpp"
static int maxListen = 1024;
class Socket//服务器客户端二合一的类
{
public:
    Socket()
        : _sockfd(-1)
    {}
    Socket(int fd)
        : _sockfd(fd)
    {}
    ~Socket()
    {
        Close();
    }
public:
    // 创建套接字
    bool CreateSocket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (_sockfd < 0)
        {
            ERROR_LOG("CREATE SOCKET FAILED!!");
            return false;
        }
        return true;
    }
    // 绑定地址信息
    bool Bind(const std::string &ip, uint16_t port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        if (bind(_sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0)
        {
            ERROR_LOG("BIND ADDRESS FAILED!");
            return false;
        }
        return true;
    }
    // 开始监听
    bool Listen(int backlog = maxListen)
    {
        if (listen(_sockfd, backlog) < 0)
        {
            ERROR_LOG("SOCKET LISTEN FAILED!");
            return false;
        }
        return true;
    }
    // 向服务器发起连接
    bool Connect(const std::string &ip, uint16_t port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        if (connect(_sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0)
        {
            ERROR_LOG(" CONNECT SERVER FAILED!");
            return false;
        }
        return true;
    }
    // 获取新连接
    int Accept()
    {
        int newfd = accept(_sockfd, nullptr, nullptr);
        if (newfd < 0)
        {
            ERROR_LOG("SOCKET ACCEPT FAILED!");
            return -1;
        }
        return newfd;
    }
    // 接收数据
    ssize_t Recv(void *buf, size_t len, int flag = 0)
    {
        ssize_t ret = recv(_sockfd, buf, len, flag);
        if (ret <= 0)
        {
            //EAGAIN:表示当前缓冲区没有数据（非阻塞）EINTR:当前socket的阻塞等待，被信号打断了
            if(errno == EAGAIN || errno == EINTR)
            {
                return 0;//表示没有接收到数据
            }
            ERROR_LOG("SOCKET RECV FAILED!");
            return -1;
        }
        return ret;
    }
    //非阻塞接收数据
    ssize_t NonBlockRecv(void *buf, size_t len)
    {
        return Recv(buf, len, MSG_DONTWAIT);//MSG_DONTWAIT:当前接收方式为非阻塞，没有数据就报错返回
    }
    // 发送数据
    ssize_t Send(const void *buf, size_t len, int flag = 0)
    {
        ssize_t ret = send(_sockfd, buf, len, flag);
        if(ret < 0)
        {
            if(errno == EAGAIN || errno == EINTR)
            {
                return 0;//表示没有接收到数据
            }
            ERROR_LOG("SOCKET SEND FAILED!");
            return -1;
        }
        return ret;//实际发送的数据长度，缓冲区数据可能没有发完
    }
    //非阻塞发送数据
    ssize_t NonBlockSend(void *buf, size_t len)
    {
        if (len == 0){ return 0; }
        return Send(buf, len, MSG_DONTWAIT);//MSG_DONTWAIT:当前发送方式为非阻塞，没有数据就报错返回
    }
    // 关闭套接字
    void Close()
    {
        if (_sockfd < 0)
        {
            close(_sockfd);
            _sockfd = -1;
        }
    }
    // 创建服务端
    bool CreateServer(uint16_t port, const std::string &ip = "0.0.0.0", bool blockFlag = false)
    {
        //1、创建套接字2、绑定地址3、开始监听4、设置非阻塞5、设置地址复用
        if (CreateSocket() == false) return false;
        if (blockFlag) NonBlock();
        if (Bind(ip, port) == false) return false;
        if (Listen() == false) return false;
        ReuseAddress();
        return true;
    }
    // 创建客户端
    bool CreateClient(uint16_t port, const std::string &ip)
    {
        //1、创建套接字2、连接服务器
        if (CreateSocket() == false) return false;
        if (Connect(ip, port) == false) return false;
        return true;
    }
    // 开启地址端口复用
    void ReuseAddress()
    {
        int opt = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        opt = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt));
    }
    // 设置套接字为非阻塞
    void NonBlock()
    {
        int flag = fcntl(_sockfd, F_GETFL, 0);
        fcntl(_sockfd, F_SETFL, flag | O_NONBLOCK);
    }
    //获取描述符,偷家函数
    int GetFd() {return _sockfd;}
private:
    int _sockfd;
};